package cn.water.luban.demo.gateway.filter;

import com.alibaba.nacos.common.utils.CollectionUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Supplier;

@Component
public class MyFilter2 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("过滤器[2]开始工作了");
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String message = "你的请求被拦截了";
        HttpHeaders headers = response.getHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        MultiValueMap<String,String> queryParams = request.getQueryParams();
        List<String> query = queryParams.get("token");
        if(CollectionUtils.isNotEmpty(query)){
            return chain.filter(exchange);
        }
        //将数据转换成二进制
        byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
        //缓冲流
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        //包装数据
        DataBuffer wrap = dataBufferFactory.wrap(bytes);
        Mono mono = Mono.fromSupplier(new Supplier<DataBuffer>() {
            @Override
            public DataBuffer get() {
                return wrap;
            }
        });
        return response.writeWith(mono);
    }

    @Override
    public int getOrder() {
        return 10;
    }
}
